package com.myproject.mall.goods.util;

import com.myproject.mall.domain.entity.Goods;
import com.myproject.mall.goods.mapper.GoodsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class RecommendUtil {
    @Autowired
    private GoodsMapper goodsMapper;

    public UserPreference analyzeUserPreference(List<Long> historyIds) {
        List<Goods> historyGoods = goodsMapper.selectByIds(historyIds);

        if(historyGoods.isEmpty()) return null;

//            偏好统计
        Map<Integer, Integer> categoryPreference = new HashMap<>();
        Map<Long, Integer> brandPreference = new HashMap<>();
        Map<Long, Integer> shopPreference = new HashMap<>();

        for (int i = 0; i<historyIds.size(); i++) {
            Long goodsId = historyIds.get(i);
            Goods goods = historyGoods.stream()
                    .filter(g -> g.getId().equals(goodsId))
                    .findFirst()
                    .orElse(null);
//                最近浏览记录的商品权值更高
            if (goods != null) {
//                    越靠前权值越高
                int weight = Math.max(1, 10-i/2);
                categoryPreference.put(goods.getCategoryId(), categoryPreference.getOrDefault(goods.getCategoryId(), 0) + weight);
                brandPreference.put(goods.getBrandId(), brandPreference.getOrDefault(goods.getBrandId(), 0) + weight);
                shopPreference.put(goods.getShopId(), shopPreference.getOrDefault(goods.getShopId(), 0) + weight);
            }
        }
        return new UserPreference(categoryPreference, brandPreference, shopPreference);
    }

}
